import sys
import time
import json
from datetime import datetime
from selenium import webdriver
from selenium.common import exceptions
from selenium.webdriver.chrome.options import Options
import urllib.parse
from mongoengine import *
from selenium.webdriver.common.action_chains import ActionChains

whiteList = ['-101','-100','4450443968889831','4044671657000761','3263330414','5581785513']



class myprivateaccounts(Document):
    name = StringField()
    uid = StringField()
    addTime = DateTimeField()
    updatetime = DateTimeField()
    isDelete = IntField()
    meta = {
        'strict':False
    }



class historychatlistuser(Document):
    nickname = StringField()
    gender = IntField()
    city = StringField()
    followerCount = IntField()
    uid = StringField()
    addTime = DateTimeField()
    accountUid = StringField()
    accountName = StringField()
    updatetime = DateTimeField()
    postCount = IntField()
    fansCount = IntField()
    searched = ListField()
    firstClickUser = ListField()
    allClickUser = ListField()
    isClicked = IntField()
    isDelete = IntField()
    lastShowDate = DateTimeField()
    meta = {
        'strict':False
    }

def NewDriver(accountName):
    chrome_options = Options()
    # chrome_options.add_argument("user-data-dir=" + path2 + 'privatelist' + accountName)
    chrome_options.add_argument("user-data-dir=" + path2 + 'searchprivate' + accountName)
    driver = webdriver.Chrome(path, options=chrome_options)
    driver.maximize_window()
    return driver


def readUserInfoImList(session):
    info = session.find_element_by_class_name('name')
    nickName = info.find_element_by_class_name('usrn').get_attribute('textContent')
    uid = info.find_element_by_class_name('hidden').get_attribute('textContent')
    top = 0
    toptags = info.find_elements_by_class_name('toptag')
    if len(toptags) != 0:
        top = 1
    date = session.find_elements_by_class_name('time')[-1].get_attribute('textContent')
    print(nickName,uid,date)
    if uid not in whiteList:
        user = historychatlistuser.objects(uid=uid,accountUid=accountList[index]["uid"])
        if len(user)==0:
            print(nickName,uid,top,date)
            newdata = historychatlistuser(
                nickname = nickName, 
                uid = uid,
                searched = [],
                addTime = datetime.now(),
                accountUid = accountList[index]["uid"],
                accountName = accountList[index]["name"],
                updatetime = datetime.now(),
                isDelete = 0,
                isClicked = 0,
                lastShowDate = datetime.now()
            )
            newdata.save()
        else:
            user = historychatlistuser.objects.get(uid=uid,accountUid=accountList[index]["uid"])
            user.updatetime = datetime.now()
            # user.isDelete = 1
            user.save()
            # newdata = chatlistuser(
            #     nickname = nickName, 
            #     uid = uid,
            #     searched = [],
            #     addTime = datetime.now(),
            #     accountUid = accountList[index]["uid"],
            #     accountName = accountList[index]["name"],
            #     updatetime = datetime.now(),
            #     isDelete = 0,
            #     isClicked = 0,
            #     lastShowDate = datetime.now()
            # )
            # newdata.save()
    if "微博" not in nickName:
        return uid,date

def scrollAndList(sessioncount):
    driver0.execute_script("arguments[0].scrollIntoView();", driver0.find_elements_by_class_name('sessionlist')[sessioncount-1])
    time.sleep(5)
    # chatList()
    # action = ActionChains(driver0)
    # action.move_to_element(driver0.find_element_by_class_name('contactslist')).perform()  


def chatList(sessioncount):
    chatUidList = []
    chatList = driver0.find_elements_by_class_name('sessionlist')
    templist = chatList[-55:]
    print(len(chatList),templist[0])
    sessioncount = len(chatList)
    if len(templist)>0:
        for session in templist:
            try:
                uid,date = readUserInfoImList(session)
                # chatUidList.append(uid)
                print(uid,date)
            except Exception as e:
                print(str(e),'error')
    



if __name__ == '__main__':
    index = int(sys.argv[1])
    # accountName = sys.argv[1]
    # accountUid = sys.argv[2]
    mode = 1
    path = 'e:/work/weiboprivate/python/chromedriver90.exe'
    path2 = 'e:/work/weiboprivate/profile/'
    if mode == 1:
        path = 'd:/weiboprivate/python/chromedriver.exe'
        path2 = 'd:/weiboprivate/profile/'
        connect('weibo', host='1.15.92.12', port=27817)
        # connect('weibo', host='localhost', port=27017)
    else:
        connect('weibo', host='1.15.92.12', port=27817)
        # connect('weibo', host='localhost', port=27017)

    accountList = myprivateaccounts.objects(isDelete=0)
    accountName = accountList[index]['name']
    accountUid = accountList[index]['uid']

    
    driver0 = NewDriver(accountName)
    driver0.get("https://weibo.com")
    driver0.get("https://api.weibo.com/chat")

    time.sleep(1)
    sessioncount = 0
    while True:
        chatList(sessioncount)
        scrollAndList(sessioncount)